var addresses =new Array();
var popup =new Array();
var geo = new GClientGeocoder(); 
var map = new GMap2(document.getElementById("map"));

var livegmap = {
	init_livegmap: function(){
		livegmap.init_google_map();
		setInterval('livegmap.getlivegmap_json()',Drupal.settings.livegmap.refresh_time*1000);
	},
	getlivegmap_json: function(){
		addresses =new Array();
		popup =new Array();
		map.clearOverlays();
		$.ajax({
  			url: Drupal.settings.basePath+"livegmap/json",
  			success: function(response){
	  			var r_data=Drupal.parseJson(response);
		  		for(var i=0;i<r_data.points.length;i++){
			  		addresses.push(r_data.points[i].address);
			  		popup.push(r_data.points[i].address);
		  		}	
		  	//init_livegmap();
			livegmap.search_address();
			
	  		}
		});	
	},
	init_google_map: function(){
		if (GBrowserIsCompatible()) { 
      		map.addControl(new GLargeMapControl());
      		map.addControl(new GMapTypeControl());
      		map.setCenter(new GLatLng(43.907787,-79.359741),1);
      		/*for(i=0;i<addresses.length;i++){
				getAddress(addresses[i],i);
	  		}*/
    	}
    	else {
      		alert("Sorry, the Google Maps API is not compatible with this browser");
    	}
	},
	search_address: function(){
		for(i=0;i<addresses.length;i++){
				livegmap.plot_address_marker(addresses[i],i);
	  	}
	},
	plot_address_marker: function(search,index){
		geo.getLocations(search, function (result)
          { 
            // If that was successful
            if (result.Status.code == G_GEO_SUCCESS) {
              // Lets assume that the first marker is the one we want
              var p = result.Placemark[0].Point.coordinates;
              var lat=p[1];
              var lng=p[0];
		
 	      var point = new GLatLng(lat,lng);
 	      var marker = livegmap.create_marker(point,popup[index]);
 	      map.addOverlay(marker);

            }
          });
	},
	create_marker: function(point,html){
		var marker = new GMarker(point);
        GEvent.addListener(marker, "click", function() {marker.openInfoWindowHtml(html);});
        return marker;	
	}
};
//alert(Drupal.settings.livegmap.refresh_time)
//get live users json data
$(document).ready(function(){
  livegmap.init_livegmap();
});
/*function init_livegmap(){
}

function createMarker(point,html) {
	 
}

function getAddress(search,index) {
        geo.getLocations(search, function (result)
          { 
            // If that was successful
            if (result.Status.code == G_GEO_SUCCESS) {
              // Lets assume that the first marker is the one we want
              var p = result.Placemark[0].Point.coordinates;
              var lat=p[1];
              var lng=p[0];
		
 	      var point = new GLatLng(lat,lng);
 	      var marker = createMarker(point,popup[index]);
 	      map.addOverlay(marker);

            }
          });
      }
    
      // JavaScript Document
	  */